﻿//! Simulate a failing oha benchmark (0% success rate)

use async_trait::async_trait;
use yansi::Paint;

use crate::args::AppConfig;
use crate::io::{csleep, dprint, newline, print};
use crate::modules::Module;

pub struct OhaFail;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use rand::Rng;
use std::thread;
use std::time::Duration;

fn bar() {
    let m = MultiProgress::new();
    let sty = ProgressStyle::with_template(
        "[{elapsed_precise}] {bar:40.cyan/blue} {pos:>7}/{len:7} {msg}",
    )
    .unwrap()
    .progress_chars("##-");

    let n = 200;
    let pb = m.add(ProgressBar::new(n));
    pb.set_style(sty.clone());
    pb.set_message("todo");
    let pb2 = m.add(ProgressBar::new(n));
    pb2.set_style(sty.clone());
    pb2.set_message("finished");

    let pb3 = m.insert_after(&pb2, ProgressBar::new(1024));
    pb3.set_style(sty);

    m.println("starting!").unwrap();

    let mut threads = vec![];

    let m_clone = m.clone();
    let h3 = thread::spawn(move || {
        for i in 0..1024 {
            thread::sleep(Duration::from_millis(2));
            pb3.set_message(format!("item #{}", i + 1));
            pb3.inc(1);
        }
        m_clone.println("pb3 is done!").unwrap();
        pb3.finish_with_message("done");
    });

    for i in 0..n {
        thread::sleep(Duration::from_millis(15));
        if i == n / 3 {
            thread::sleep(Duration::from_secs(2));
        }
        pb.inc(1);
        let pb2 = pb2.clone();
        threads.push(thread::spawn(async move || {
            let num = rand::thread_rng().gen_range(0..100);
            csleep(num).await;
            pb2.inc(1);
        }));
    }
    pb.finish_with_message("all jobs started");

    for thread in threads {
        let _ = thread.join();
    }
    let _ = h3.join();
    pb2.finish_with_message("all jobs done");
    m.clear().unwrap();
}
#[async_trait(?Send)]
impl Module for OhaFail {
    fn name(&self) -> &'static str {
        "oha-fail"
    }

    fn signature(&self) -> String {
        "oha -n 1000 http://127.0.0.1:9".to_string()
    }

    async fn run(&self, appconfig: &AppConfig) {
        bar();
        newline().await;
        print(Paint::cyan("Summary:").bold().to_string()).await;
        newline().await;
        dprint(format!("  Success rate:\t{}", Paint::red("0.00%")), 10).await;
        newline().await;

        dprint("  Total:\t1.8178 secs".to_string(), 10).await;
        newline().await;

        dprint("  Slowest:\t-inf secs".to_string(), 10).await;
        newline().await;

        dprint(Paint::green("  Fastest:\tinf secs").to_string(), 10).await;
        newline().await;

        dprint("  Average:\tNaN secs".to_string(), 10).await;
        newline().await;

        dprint("  Requests/sec:\t23.6546".to_string(), 10).await;

        newline().await;

        dprint("  Total data:\t0 B".to_string(), 10).await;
        newline().await;

        dprint("  Size/request:\tNaN".to_string(), 10).await;
        newline().await;

        dprint("  Size/sec:\t0 B".to_string(), 10).await;

        newline().await;

        print(Paint::cyan("Response time histogram:").bold().to_string()).await;
        newline().await;
        for _ in 0..10 {
            dprint("  NaN [0]  |".to_string(), 10).await;
            newline().await; 
            if appconfig.should_exit() {
                return ; 
            }
        }

        newline().await;

        print(
            Paint::cyan("Response time distribution:")
                .bold()
                .to_string(),
        )
        .await;
        newline().await;
        for p in &[
            "10.00", "25.00", "50.00", "75.00", "90.00", "95.00", "99.00", "99.90", "99.99",
        ] {
            dprint(format!("  {}% in {}", p, Paint::red("NaN secs")), 10).await;

            newline().await;
        }

        newline().await;

        dprint(
            Paint::cyan("Details (average, fastest, slowest):")
                .bold()
                .to_string(),
            10,
        )
        .await;

        newline().await;
        dprint(
            "  DNS+dialup:\tNaN secs, inf secs, -inf secs".to_string(),
            10,
        )
        .await;

        newline().await;
        dprint(
            "  DNS+lookup:\tNaN secs, inf secs, -inf secs".to_string(),
            10,
        )
        .await;

        newline().await;
        dprint(
            Paint::green("Finished with 0 successful responses").to_string(),
            10,
        )
        .await;
        newline().await;
    }
}
